from Aes import DeCodeByAESCBC, EnCodeByAESCBC
import random

#读取文件
def ReadFile(file):
    data = open(file, encoding='utf-8').read()
    return data

def Bxor(b1, b2): # use xor for bytes
    parts = []
    for b1, b2 in zip(b1, b2):
        parts.append(bytes([b1 ^ b2]))
    return b''.join(parts)

#随机数
def RandomBySeed(seed):
    seed1 = seed[1]
    s1 = RandomBySingleSeed(seed1)
    seed2 = seed[0]
    s2 =  RandomBySingleSeed(seed2)
    s = s1 + s2
    return s

def RandomBySingleSeed(seed):
    random.seed(seed)
    r = random.random()
    s = str(r)
    s = bytes(s, encoding = "utf8")
    s = s[10:]
    return s

#加密
def EncodeMainTextByAESCBC(text, key, IV):
    #读取文件
    text = ReadFile(text)
    text = text.encode("utf-8")

    #用AESCBC加密
    text = EncodeAllTextByAESCBC(text, key, IV)
    return text

def EncodeMainKeyByAESCBC(keyword, key, IV):
    #标准化
    #单个关键词<16个汉字
    text = Standardkey(keyword)
    
    #用AESCBC加密
    text = EncodeAllTextByAESCBC(text, key, IV)
    return text

def EncodeAllTextByAESCBC(text, key, IV):
    #添0.使其长为48的整数倍
    while(len(text)%48 != 0):
        text += b"0"
    ciper = b""
    while(len(text) != 0):
        plain = text[:16]
        text = text[16:]
        plain = EnCodeByAESCBC(plain, key, IV)
        ciper += plain
    return ciper

def Standardkey(text):
    #每个关键词添0，使其bytes长为48（关键词长<16）
    text = ReadFile(text)
    key = ""
    k = ""
    long = 0
    for i in text:
        if(i != ";"):
            k += i
        else:
            k += i
            if(len(k.encode()) <= 48):
                while(len(k.encode()) != 48):
                    k += "0"
            else:
                long += 1
                k = ""
            key += k
            k = ""
    if(long != 0):
        print("有太长的关键词")
        print("存储时已删除")
    key = key.encode()
    return key

#解密
def DecodeAllTextByAESCBC(text, key, IV):
    ciper = b""
    while(len(text) != 0):
        encodetext = text[:16]
        text = text[16:]
        encodetext = DeCodeByAESCBC(encodetext, key, IV)
        ciper += encodetext
    return ciper

#消0
def EliminatingPadding(text):
    while(text[len(text)-1] == "0"):
        text = text[:(len(text)-1)]
    return text

def EliminatingBytePadding(text):
    
    while(text[len(text)-1] == 48):
        text = text[:(len(text)-1)]
        
    return text
